package com.hao.imserver.websocketserver;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.hao.imserver.cache.ICacheService;
import com.hao.imserver.model.Message;

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    private static ApplicationContext applicationContext;
    
    public static void setApplicationContext(ApplicationContext applicationContext) {
	WebSocketServer.applicationContext = applicationContext;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
	getCacheService().put(session);
	log.info("有新连接加入！当前在线人数为" + onlineCount.incrementAndGet());
	Message m = new Message(session.getId(), session.getId(), "连接成功", new Date().getTime());
//	sendMessage(session, "连接成功");
	sendMessage(m);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
	getCacheService().remove(session);
	log.info("有一连接关闭！当前在线人数为" + onlineCount.decrementAndGet());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
	log.info("来自客户端的消息:" + message);
	sendInfo(session, message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
	log.error("发生错误");
	error.printStackTrace();
    }

    public void sendMessage(Session session, String message) {
	try {
	    session.getBasicRemote().sendText(message);
	} catch (IOException e) {
	    log.debug("{}", "发送失败");
	    e.printStackTrace();
	}
    }
    
    public void sendMessage(Message msg) {
	Session session = getCacheService().find(msg.getTo());
   	try {
   	    session.getBasicRemote().sendText(msg.toString());
   	} catch (IOException e) {
   	    log.debug("{}", "发送失败");
   	    e.printStackTrace();
   	}
       }

    /**
     * 群发自定义消息
     */
    public void sendInfo(Session session, String message) {
	getCacheService().getAll().stream().parallel().forEach(s->{
	    sendMessage(s, message);
	});
    }
    
    private ICacheService getCacheService() {
	return (ICacheService) applicationContext.getBean("cacheServiceImpl");
    }
    
}
